import React from 'react';
import ReactECharts from 'echarts-for-react';

interface EchartsColumnProps {
  data: any[];
  xField: string;
  yField: string;
  height?: number;
  color?: string;
  columnWidthRatio?: number;
  meta?: {
    [key: string]: {
      alias?: string;
    };
  };
  [key: string]: any;
}

const EchartsColumn: React.FC<EchartsColumnProps> = ({
  data = [],
  xField,
  yField,
  height = 400,
  color = '#1890ff',
  columnWidthRatio = 0.6,
  meta,
  ...rest
}) => {
  // 确保 data 是数组
  const safeData = Array.isArray(data) ? data : [];

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0];
        const xAlias = meta?.[xField]?.alias || xField;
        const yAlias = meta?.[yField]?.alias || yField;
        return `${xAlias}: ${param.axisValue}<br/>${yAlias}: ${param.value}`;
      },
    },
    xAxis: {
      type: 'category',
      data: safeData.map(item => item[xField]),
      name: meta?.[xField]?.alias || xField,
    },
    yAxis: {
      type: 'value',
      name: meta?.[yField]?.alias || yField,
    },
    series: [
      {
        data: safeData.map(item => item[yField]),
        type: 'bar',
        itemStyle: {
          color,
        },
        barWidth: `${columnWidthRatio * 100}%`,
      },
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
  };

  return (
    <ReactECharts
      option={option}
      style={{ height: `${height}px`, width: '100%' }}
      {...rest}
    />
  );
};

export default EchartsColumn;
